<template>
  <div class="assets-transfer-container">
    <div class="search-area">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="资产名称">
          <el-input v-model="searchForm.assets_name" placeholder="请输入资产名称" clearable />
        </el-form-item>
        <el-form-item label="调拨状态">
          <el-select v-model="searchForm.status" placeholder="请选择调拨状态" clearable>
            <el-option label="待审批" value="待审批" />
            <el-option label="已审批" value="已审批" />
            <el-option label="已调拨" value="已调拨" />
            <el-option label="已拒绝" value="已拒绝" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadData">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="action-area">
      <el-button type="primary" plain @click="showAddDialog">新增调拨</el-button>
      <el-button type="success" plain @click="exportData">导出数据</el-button>
    </div>

    <div class="table-area">
      <el-table :data="tableData" border stripe>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="assets_name" label="资产名称" />
        <el-table-column prop="assets_no" label="资产编号" />
        <el-table-column prop="from_staff_name" label="原使用人" />
        <el-table-column prop="from_department_name" label="原使用部门" />
        <el-table-column prop="to_staff_name" label="现使用人" />
        <el-table-column prop="to_department_name" label="现使用部门" />
        <el-table-column prop="reason" label="调拨原因" />
        <el-table-column prop="transfer_time" label="调拨时间" :formatter="(row,col,val)=>$fmtDate(val)" />
        <el-table-column prop="transfer_staff_name" label="调拨人" />
        <el-table-column prop="status" label="调拨状态">
          <template v-slot="scope">
            <el-tag :type="getStatusTagType(scope.row.status)">{{ scope.row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="approver_name" label="审批人" />
        <el-table-column prop="approve_time" label="审批时间" :formatter="(row,col,val)=>$fmtDate(val)" />
        <el-table-column label="操作" width="220">
          <template v-slot="scope">
            <el-button size="mini" type="primary" plain @click="showEditDialog(scope.row)">编辑</el-button>
            <el-button size="mini" type="success" plain @click="showApproveDialog(scope.row)" v-if="scope.row.status==='待审批' && user.role==='ADMIN'">审批</el-button>
            <el-button size="mini" type="danger" plain @click="deleteItem(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.pageNum"
        :page-sizes="[10,20,50,100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total" />

    <!-- 新增/编辑 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="form" :rules="rules" ref="form" label-width="100px">
        <el-form-item label="资产" prop="assets_id">
          <el-select v-model="form.assets_id" placeholder="请选择资产" filterable @change="handleAssetChange">
            <el-option v-for="item in assetsList" :key="item.id"
                       :label="`${item.name} (${item.no})`" :value="item.id" />
          </el-select>
        </el-form-item>
        <div v-if="selectedAsset" class="asset-info">
          <div><strong>当前使用人：</strong>{{ selectedAsset.staff_name || '无' }}</div>
          <div><strong>当前使用部门：</strong>{{ selectedAsset.departmentName || '无' }}</div>
        </div>
        <el-form-item label="调拨时间" prop="transfer_time">
          <el-date-picker v-model="form.transfer_time" type="datetime" placeholder="选择调拨时间" />
        </el-form-item>
        <el-form-item label="新使用部门" prop="to_department_id">
          <el-select v-model="form.to_department_id" placeholder="请选择新使用部门" filterable>
            <el-option v-for="d in departmentList" :key="d.id" :label="d.name" :value="d.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="新使用人" prop="to_staff_id">
          <el-select v-model="form.to_staff_id" placeholder="请选择新使用人" filterable>
            <el-option v-for="s in staffList" :key="s.id" :label="s.name" :value="s.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="调拨原因" prop="reason">
          <el-input type="textarea" v-model="form.reason" :rows="3" placeholder="请输入调拨原因" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button size="mini" type="success" plain @click="dialogVisible=false">取 消</el-button>
        <el-button size="mini" type="primary" plain @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 审批 -->
    <el-dialog title="审批调拨申请" :visible.sync="approveDialogVisible" width="500px">
      <el-form :model="approveForm" ref="approveForm" label-width="100px">
        <el-form-item label="审批结果">
          <el-radio-group v-model="approveForm.status">
            <el-radio label="已审批">同意</el-radio>
            <el-radio label="已拒绝">拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审批意见">
          <el-input type="textarea" v-model="approveForm.approve_comment" placeholder="请输入审批意见" />
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="approveDialogVisible=false">取 消</el-button>
        <el-button type="primary" @click="submitApprove">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'AssetsTransfer',
  data() {
    return {
      user: JSON.parse(localStorage.getItem('xm-user') || '{}'),
      searchForm: { assets_name: '', status: '' },
      tableData: [],
      pagination: { pageNum: 1, pageSize: 10, total: 0 },
      dialogVisible: false,
      dialogTitle: '新增调拨',
      assetsList: [],
      departmentList: [],
      staffList: [],
      selectedAsset: null,
      form: { id: null, assets_id: null, transfer_time: '', from_staff_id: null, from_department_id: null,
        to_staff_id: null, to_department_id: null, reason: '' },
      rules: {
        assets_id: [{ required: true, message: '请选择资产', trigger: 'change' }],
        transfer_time: [{ required: true, message: '请选择调拨时间', trigger: 'change' }],
        to_department_id: [{ required: true, message: '请选择新使用部门', trigger: 'change' }],
        to_staff_id: [{ required: true, message: '请选择新使用人', trigger: 'change' }],
        reason: [{ required: true, message: '请输入调拨原因', trigger: 'blur' }]
      },
      approveDialogVisible: false,
      approveForm: { id: null, status: '已审批', approve_comment: '' }
    }
  },
  created() {
    this.loadData()
    this.loadAssetsList()
    this.loadDepartmentList()
    this.loadStaffList()
  },
  methods: {
    async loadData() {
      this.selectedAsset = null
      try {
        const params = { pageNum: this.pagination.pageNum, pageSize: this.pagination.pageSize, ...this.searchForm }
        const res = await this.$request.get('/assetsTransfer/selectPage', { params })
        if (res.code === '200') {
          this.tableData = res.data.list
          this.pagination.total = res.data.total
        }
      } catch (e) {
        console.error(e)
        this.$message.error('数据加载失败')
      }
    },
    resetSearch() {
      this.searchForm = { assets_name: '', status: '' }
      this.loadData()
    },
    showAddDialog() {
      this.dialogTitle = '新增调拨'
      this.selectedAsset = null
      this.form = { id: null, assets_id: null, transfer_time: '', from_staff_id: null, from_department_id: null,
        to_staff_id: null, to_department_id: null, reason: '' }
      this.dialogVisible = true
    },
    showEditDialog(row) {
      this.dialogTitle = '编辑调拨'
      this.selectedAsset = null
      this.form = { ...row }
      this.dialogVisible = true
    },
    showApproveDialog(row) {
      this.approveForm = { id: row.id, status: '已审批', approve_comment: '' }
      this.approveDialogVisible = true
    },
    async loadAssetsList() {
      const res = await this.$request.get('/assets/selectAll')
      if (res.code === '200') this.assetsList = res.data || []
    },
    async loadDepartmentList() {
      const res = await this.$request.get('/department/selectAll')
      if (res.code === '200') this.departmentList = res.data || []
    },
    async loadStaffList() {
      const res = await this.$request.get('/staff/selectAll')
      if (res.code === '200') this.staffList = res.data || []
    },
    handleAssetChange(assetId) {
      const asset = this.assetsList.find(v => v.id === assetId)
      if (asset) {
        this.selectedAsset = asset
        this.form.from_staff_id = asset.staff_id
        this.form.from_department_id = asset.departmentId
      } else {
        this.selectedAsset = null
        this.form.from_staff_id = null
        this.form.from_department_id = null
      }
    },
    submitForm() {
      this.$refs.form.validate(async valid => {
        if (!valid) return
        try {
          const data = { ...this.form,
            from_staff_name: this.selectedAsset?.staff_name || '',
            from_department_name: this.selectedAsset?.departmentName || '',
            to_staff_name: this.staffList.find(v=>v.id===this.form.to_staff_id)?.name||'',
            to_department_name: this.departmentList.find(v=>v.id===this.form.to_department_id)?.name||''
          }
          if (this.form.id) {
            await this.$request.put('/assetsTransfer/update', data)
            this.$message.success('更新成功')
          } else {
            await this.$request.post('/assetsTransfer/add', data)
            this.$message.success('新增成功')
          }
          this.dialogVisible = false
          await this.loadData()
        } catch (e) {
          this.$message.error('操作失败')
        }
      })
    },
    async submitApprove() {
      try {
        await this.$request.post('/assetsTransfer/approve', null, { params: this.approveForm })
        this.$message.success('审批成功')
        this.approveDialogVisible = false
        this.loadData()
      } catch (e) {
        this.$message.error('审批失败')
      }
    },
    async deleteItem(id) {
      try {
        await this.$confirm('确定删除该记录？', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' })
        await this.$request.delete(`/assetsTransfer/delete/${id}`)
        this.$message.success('删除成功')
        this.loadData()
      } catch (e) {
        if (e !== 'cancel') this.$message.error('删除失败')
      }
    },
    exportData() {
      window.open(this.$baseUrl + '/assetsTransfer/export', '_blank')
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.loadData()
    },
    handleCurrentChange(val) {
      this.pagination.pageNum = val
      this.loadData()
    },
    getStatusTagType(status) {
      const map = { '已调拨': 'success', '已审批': 'warning', '待审批': 'info', '已拒绝': 'danger' }
      return map[status] || ''
    }
  }
}
</script>

<style scoped>
.assets-transfer-container{padding:20px}

.search-area,.action-area,

.table-area{background:#fff;padding:20px;border-radius:8px;margin-bottom:20px;box-shadow:0 2px 12px rgba(0,0,0,.05)}

.asset-info{margin-bottom:20px;padding:10px;background:#f5f7fa;border-radius:4px}
</style>